package com.rongzhe.house.user.controller;


import com.rongzhe.house.common.constants.Constants;
import com.rongzhe.house.common.exception.RongZheBusinessException;
import com.rongzhe.house.common.resp.ApiResult;
import com.rongzhe.house.common.rest.BaseController;
import com.rongzhe.house.house.entity.HouseBase;
import com.rongzhe.house.user.entity.*;
import com.rongzhe.house.user.service.UserHouseAppointmentService;
import com.rongzhe.house.user.service.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by JackWangon[www.coder520.com] 2017/7/27.
 */
@Slf4j
@RestController
@RequestMapping("user")
public class UserController extends BaseController {

    @Autowired
    @Qualifier("userServiceImpl")
    private UserService userService;

    @Autowired
    private UserHouseAppointmentService userHouseAppointmentService;


    /**
     * @Author JackWang [www.coder520.com]
     * @Date 2017/8/2 22:03
     * @Description 用户登录（注册）
     */
    @ApiOperation(value = "用户登录", notes = "用户登录", httpMethod = "POST")
    @ApiImplicitParam(name = "loginInfo", value = "加密数据", required = true, dataType = "LoginInfo")
    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ApiResult login(@RequestBody LoginInfo loginInfo) {

        ApiResult<String> resp = new ApiResult<>();
        try {
            /*String data = loginInfo.getData();
            String key = loginInfo.getKey();
            if (data == null) {
                throw new RongZheBusinessException("非法请求");
            }*/


            if (loginInfo.getDevice() == null) {
                resp.setCode(Constants.RESP_STATUS_BADREQUEST);
                resp.setMessage("参数错误,请传入设备信息");
                return resp;
            }

            String token = userService.login(loginInfo);
            resp.setData(token);
        } catch (RongZheBusinessException e) {
            resp.setCode(e.getStatusCode());
            resp.setMessage(e.getMessage());
        } catch (Exception e) {
            log.error("Fail to login", e);
            resp.setCode(Constants.RESP_STATUS_INTERNAL_ERROR);
            resp.setMessage("内部错误");
        }
        return resp;
    }


    /**
     * @Author JackWang [www.coder520.com]
     * @Date 2017/8/4 11:38
     * @Description 修改用户昵称
     */
    @ApiOperation(value = "修改昵称", notes = "用户修改昵称", httpMethod = "POST")
    @ApiImplicitParam(name = "user", value = "用户信息 包含昵称", required = true, dataType = "User")
    @RequestMapping("/modifyNickName")
    public ApiResult modifyNickName(@RequestBody UserBase user) {

        ApiResult<String> resp = new ApiResult<>();
        try {
            UserElement ue = getCurrentUser();
            user.setId(ue.getUserId());
            userService.modifyNickName(user);
            resp.setMessage("更新成功");
        } catch (RongZheBusinessException e) {
            resp.setCode(e.getStatusCode());
            resp.setMessage(e.getMessage());
        } catch (Exception e) {
            log.error("Fail to update user info", e);
            resp.setCode(Constants.RESP_STATUS_INTERNAL_ERROR);
            resp.setMessage("内部错误");
        }

        return resp;
    }

    /**
     * @Author JackWang [www.coder520.com]
     * @Date 2017/8/5 17:15
     * @Description 发送验证码
     */
    @ApiOperation(value = "短信验证码", notes = "根据用户手机号码发送验证码", httpMethod = "POST")
    @ApiImplicitParam(name = "user", value = "用户信息 包含手机号码", required = true, dataType = "User")
    @RequestMapping("/sendVercode")
    public ApiResult sendVercode(@RequestBody UserBase user, HttpServletRequest request) {
        ApiResult<String> resp = new ApiResult<>();
        try {
            if (StringUtils.isEmpty(user.getMobile())) {
                throw new RongZheBusinessException("手机号码不能为空");
            }
            userService.sendVercode(user.getMobile(), getIpFromRequest(request));
            resp.setMessage("发送成功");
        } catch (RongZheBusinessException e) {
            resp.setCode(e.getStatusCode());
            resp.setMessage(e.getMessage());
        } catch (Exception e) {
            log.error("Fail to update user info", e);
            resp.setCode(Constants.RESP_STATUS_INTERNAL_ERROR);
            resp.setMessage("内部错误");
        }

        return resp;
    }

    /**
     * @Author JackWang [www.coder520.com]
     * @Date 2017/8/5 0:59
     * @Description 修改头像
     */
    @ApiOperation(value = "上传头像", notes = "用户上传头像 file", httpMethod = "POST")
    @RequestMapping(value = "/uploadHeadImg", method = RequestMethod.POST)
    public ApiResult<String> uploadHeadImg(HttpServletRequest req, @RequestParam(required = false) MultipartFile file) {

        ApiResult<String> resp = new ApiResult<>();
        try {
            UserElement ue = getCurrentUser();
            String avatar = userService.uploadHeadImg(file, ue.getUserId());
            resp.setData(avatar);
            resp.setMessage("上传成功");
        } catch (RongZheBusinessException e) {
            resp.setCode(e.getStatusCode());
            resp.setMessage(e.getMessage());
        } catch (Exception e) {
            log.error("Fail to update user info", e);
            resp.setCode(Constants.RESP_STATUS_INTERNAL_ERROR);
            resp.setMessage("内部错误");
        }
        return resp;
    }

    /**
     * 获取当前登录用户的用户信息
     *
     * @return
     */
    @ApiOperation(value = "获取用户信息", httpMethod = "GET")
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
    public ApiResult<UserBase> getUserInfo() {
        ApiResult<UserBase> resp = new ApiResult<>();
        UserElement ue = getCurrentUser();
        if (ue == null) {
            resp.setCode(Constants.RESP_STATUS_NOAUTH);
            resp.setMessage("请登录!");
            return resp;
        }
        try {
            resp.setData(userService.findById(ue.getUserId()));
            resp.setMessage("获取成功!");
        } catch (RongZheBusinessException e) {
            resp.setCode(Constants.RESP_STATUS_INTERNAL_ERROR);
            resp.setMessage(e.getMessage());
        }
        return resp;
    }

    @ApiOperation(value = "预约", httpMethod = "POST")
    @ApiImplicitParam(name = "userHouseAppointment", value = "预约信息", required = true, dataType = "UserHouseAppointment")
    @RequestMapping(value = "/houseAppointment", method = RequestMethod.POST)
    public ApiResult houseAppointment(@RequestBody UserHouseAppointment userHouseAppointment) throws RongZheBusinessException {
        ApiResult resp = new ApiResult<>();
        try{
            userHouseAppointment.setInsertUid(getCurrentUser().getUserId());
        }catch (Exception e){

        }
        userHouseAppointmentService.appointment(userHouseAppointment);


        return resp;
    }


    @ApiOperation(value = "预约列表", httpMethod = "GET")
    @RequestMapping(value = "/houseAppointment/list", method = RequestMethod.GET)
    public ApiResult<List<UserHouseAppointment>> houseAppointmentList(
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,
            @RequestParam(value = "state", defaultValue = "1") Integer status
    ) throws RongZheBusinessException {
        ApiResult<List<UserHouseAppointment>> resp = new ApiResult<>();


        resp.setData(userHouseAppointmentService.getAppointmentByUid(getCurrentUser().getUserId(), pageSize, currentPage, status));


        return resp;
    }


    @ApiOperation(value = "身份证认证", httpMethod = "POST")
    @RequestMapping(value = "/identifyCard", method = RequestMethod.POST)
    public ApiResult identifyCard(@RequestBody UserIdentifyCardInfo userIdentifyCardInfo) throws RongZheBusinessException {
        ApiResult resp = new ApiResult<>();

        UserElement userElement = getCurrentUser();
        if (userElement == null) {
            resp.setCode(Constants.RESP_STATUS_NOAUTH);
            resp.setMessage("请登录!");
            return resp;
        }

        userIdentifyCardInfo.setUid(userElement.getUserId());
        resp.setData(userService.addIdentifyCard(userIdentifyCardInfo));


        return resp;
    }


    @ApiOperation(value = "获取当前用户的身份证认证", httpMethod = "POST")
    @RequestMapping(value = "/identifyCard/get", method = RequestMethod.GET)
    public ApiResult identifyCard() throws RongZheBusinessException {
        ApiResult resp = new ApiResult<>();

        UserElement userElement = getCurrentUser();
        if (userElement == null) {
            resp.setCode(Constants.RESP_STATUS_NOAUTH);
            resp.setMessage("请登录!");
            return resp;
        }
        resp.setData(userService.getIdentifyCardInfoByUid(userElement.getUserId()));


        return resp;
    }


    @ApiOperation(value = "投诉建议", httpMethod = "POST")
    @RequestMapping(value = "/userComplaintSuggest", method = RequestMethod.POST)
    public ApiResult userComplaintSuggest(@RequestBody UserComplaintSuggest userComplaintSuggest) throws RongZheBusinessException {
        ApiResult resp = new ApiResult<>();
        UserElement userElement = getCurrentUser();
        if (userElement == null) {
            resp.setCode(Constants.RESP_STATUS_NOAUTH);
            resp.setMessage("请登录!");
            return resp;
        }

        userComplaintSuggest.setUid(userElement.getUserId());
        userComplaintSuggest.setInsertUid(userElement.getUserId());
        resp.setData(userService.complaintSuggest(userComplaintSuggest));


        return resp;
    }


    @ApiOperation(value = "投诉建议", httpMethod = "GET")
    @RequestMapping(value = "/userComplaintSuggest/list", method = RequestMethod.GET)
    public ApiResult userComplaintSuggest(@RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,
                                          @RequestParam(value = "pageSize", defaultValue = "1") Integer pageSize)
            throws RongZheBusinessException {
        ApiResult resp = new ApiResult<>();

        resp.setData(userService.getComplaintSuggest(currentPage, pageSize, getCurrentUser().getUserId()));


        return resp;
    }


    @ApiOperation(value = "我的合同", httpMethod = "GET")
    @RequestMapping(value = "/contract/list", method = RequestMethod.GET)
    public ApiResult contractList(@RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,
                                  @RequestParam(value = "pageSize", defaultValue = "1") Integer pageSize)
            throws RongZheBusinessException {
        ApiResult resp = new ApiResult<>();
        resp.setData(userService.contractList(currentPage, pageSize, getCurrentUser().getUserId().toString()));
        return resp;
    }


    @ApiOperation(value = "我的合同", httpMethod = "GET")
    @RequestMapping(value = "/contract/confirm")
    public ApiResult contractList(@RequestBody HouseBase houseBase)
            throws RongZheBusinessException {
        if(null==houseBase.getId()){
            return ApiResult.buildFail("参数错误");
        }
        userService.confirmContract(houseBase.getId());
        return ApiResult.buildOk();
    }

    @ApiOperation(value = "我的房源列表", httpMethod = "POST")
    @RequestMapping(value = "/contract/userHouse", method = RequestMethod.POST)
    public ApiResult userHouse() throws RongZheBusinessException {
        ApiResult resp = new ApiResult<>();
        resp.setData(userService.queryUserHouse(getCurrentUser().getUserId().toString()));
        return resp;
    }
}
